<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="header-title">系统设置</span>
      </div>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form ref="basicForm" :model="basicForm" :rules="basicRules" label-width="130px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="系统标题" prop="systemTitle">
                  <el-input v-model="basicForm.systemTitle" placeholder="请输入系统标题" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="系统简称" prop="systemShortTitle">
                  <el-input v-model="basicForm.systemShortTitle" placeholder="请输入系统简称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="管理部门" prop="departmentId">
                  <el-select v-model="basicForm.departmentId" placeholder="请选择管理部门" style="width: 100%">
                    <el-option
                      v-for="dept in departmentOptions"
                      :key="dept.id"
                      :label="dept.name"
                      :value="dept.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="技术支持电话" prop="supportPhone">
                  <el-input v-model="basicForm.supportPhone" placeholder="请输入技术支持电话" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="系统描述" prop="systemDescription">
                  <el-input
                    v-model="basicForm.systemDescription"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入系统描述信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="系统版权信息" prop="copyrightInfo">
                  <el-input v-model="basicForm.copyrightInfo" placeholder="请输入版权信息" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备案信息" prop="icp">
                  <el-input v-model="basicForm.icp" placeholder="请输入备案信息" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="submitBasicForm">保存基本设置</el-button>
              <el-button @click="resetForm('basicForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 外观设置 -->
        <el-tab-pane label="外观设置" name="appearance">
          <el-form ref="appearanceForm" :model="appearanceForm" :rules="appearanceRules" label-width="130px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="系统Logo" prop="logoUrl">
                  <image-upload v-model="appearanceForm.logoUrl" :limit="1" :multiple="false" />
                  <div class="el-upload-tip">建议上传透明背景的PNG格式图片，尺寸建议为200x60像素</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录页Logo" prop="loginLogoUrl">
                  <image-upload v-model="appearanceForm.loginLogoUrl" :limit="1" :multiple="false" />
                  <div class="el-upload-tip">建议上传透明背景的PNG格式图片，尺寸建议为200x200像素</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="系统图标" prop="faviconUrl">
                  <image-upload v-model="appearanceForm.faviconUrl" :limit="1" :multiple="false" />
                  <div class="el-upload-tip">建议上传ICO或PNG格式图片，尺寸建议为32x32或16x16像素</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录背景图" prop="loginBackgroundUrl">
                  <image-upload v-model="appearanceForm.loginBackgroundUrl" :limit="1" :multiple="false" />
                  <div class="el-upload-tip">建议上传高质量图片，尺寸建议为1920x1080像素</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="主题色" prop="themeColor">
                  <el-color-picker v-model="appearanceForm.themeColor" show-alpha></el-color-picker>
                  <span class="color-value">{{ appearanceForm.themeColor }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="侧边栏主题" prop="sideTheme">
                  <el-radio-group v-model="appearanceForm.sideTheme">
                    <el-radio label="theme-dark">深色主题</el-radio>
                    <el-radio label="theme-light">浅色主题</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="显示标签栏" prop="tagsView">
                  <el-switch v-model="appearanceForm.tagsView"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="固定Header" prop="fixedHeader">
                  <el-switch v-model="appearanceForm.fixedHeader"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="submitAppearanceForm">保存外观设置</el-button>
              <el-button @click="resetForm('appearanceForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 功能设置 -->
        <el-tab-pane label="功能设置" name="feature">
          <el-form ref="featureForm" :model="featureForm" :rules="featureRules" label-width="130px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="启用用户注册" prop="enableRegister">
                  <el-switch v-model="featureForm.enableRegister"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启用记住我" prop="enableRememberMe">
                  <el-switch v-model="featureForm.enableRememberMe"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="密码过期天数" prop="passwordExpireDays">
                  <el-input-number v-model="featureForm.passwordExpireDays" :min="0" :max="365"></el-input-number>
                  <span class="form-tip">0表示永不过期</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码最小长度" prop="passwordMinLength">
                  <el-input-number v-model="featureForm.passwordMinLength" :min="6" :max="20"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="密码复杂度" prop="passwordComplexity">
                  <el-select v-model="featureForm.passwordComplexity" placeholder="请选择密码复杂度" style="width: 100%">
                    <el-option label="低(仅限制长度)" value="low"></el-option>
                    <el-option label="中(字母+数字)" value="medium"></el-option>
                    <el-option label="高(大小写字母+数字+特殊字符)" value="high"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录失败锁定次数" prop="loginFailLockCount">
                  <el-input-number v-model="featureForm.loginFailLockCount" :min="0" :max="10"></el-input-number>
                  <span class="form-tip">0表示不启用锁定</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="启用水印" prop="enableWatermark">
                  <el-switch v-model="featureForm.enableWatermark"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="featureForm.enableWatermark">
                <el-form-item label="水印内容" prop="watermarkContent">
                  <el-input v-model="featureForm.watermarkContent" placeholder="请输入水印内容"></el-input>
                  <span class="form-tip">支持{用户名}、{部门}、{时间}变量</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="primary" @click="submitFeatureForm">保存功能设置</el-button>
              <el-button @click="resetForm('featureForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { listConfig, updateConfig, batchSaveConfig } from "@/api/system/config";

export default {
  name: "SystemConfig",
  data() {
    return {
      // 激活的标签页
      activeTab: "basic",
      // 部门选项
      departmentOptions: [],
      // 加载状态
      loading: false,

      // 基本设置表单
      basicForm: {
        systemTitle: "",
        systemShortTitle: "",
        departmentId: null,
        supportPhone: "",
        systemDescription: "",
        copyrightInfo: "",
        icp: ""
      },
      // 基本设置表单验证规则
      basicRules: {
        systemTitle: [
          { required: true, message: "系统标题不能为空", trigger: "blur" },
          { min: 2, max: 50, message: "系统标题长度在2到50个字符之间", trigger: "blur" }
        ],
        systemShortTitle: [
          { required: true, message: "系统简称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "系统简称长度在2到20个字符之间", trigger: "blur" }
        ],
        departmentId: [
          { required: true, message: "请选择管理部门", trigger: "change" }
        ],
        supportPhone: [
          { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ]
      },

      // 外观设置表单
      appearanceForm: {
        logoUrl: "",
        loginLogoUrl: "",
        faviconUrl: "",
        loginBackgroundUrl: "",
        themeColor: "#409EFF",
        sideTheme: "theme-dark",
        tagsView: true,
        fixedHeader: true
      },
      // 外观设置表单验证规则
      appearanceRules: {
        logoUrl: [
          { required: true, message: "请上传系统Logo", trigger: "change" }
        ],
        themeColor: [
          { required: true, message: "请选择主题色", trigger: "change" }
        ]
      },

      // 功能设置表单
      featureForm: {
        enableRegister: false,
        enableRememberMe: true,
        passwordExpireDays: 90,
        passwordMinLength: 8,
        passwordComplexity: "medium",
        loginFailLockCount: 5,
        enableWatermark: false,
        watermarkContent: "{用户名} {部门} {时间}"
      },
      // 功能设置表单验证规则
      featureRules: {
        passwordMinLength: [
          { required: true, message: "请设置密码最小长度", trigger: "blur" }
        ],
        passwordComplexity: [
          { required: true, message: "请选择密码复杂度", trigger: "change" }
        ],
        watermarkContent: [
          { required: true, message: "启用水印时，水印内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDepartmentList();
    this.getConfigData();
  },
  methods: {
    /** 获取部门列表 */
    getDepartmentList() {
      listDept().then(response => {
        this.departmentOptions = response.data;
      });
    },

    /** 获取配置数据 */
    getConfigData() {
      this.loading = true;
      listConfig().then(response => {
        const configs = response.data || [];
        // 处理配置数据，填充到表单中
        this.processConfigData(configs);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 处理配置数据 */
    processConfigData(configs) {
      configs.forEach(config => {
        // 根据配置键和类型分配到对应的表单字段
        switch (config.configKey) {
          // 基本设置
          case "system.title":
            this.basicForm.systemTitle = config.configValue;
            break;
          case "system.short.title":
            this.basicForm.systemShortTitle = config.configValue;
            break;
          case "system.department.id":
            this.basicForm.departmentId = parseInt(config.configValue) || null;
            break;
          case "system.support.phone":
            this.basicForm.supportPhone = config.configValue;
            break;
          case "system.description":
            this.basicForm.systemDescription = config.configValue;
            break;
          case "system.copyright":
            this.basicForm.copyrightInfo = config.configValue;
            break;
          case "system.icp":
            this.basicForm.icp = config.configValue;
            break;

          // 外观设置
          case "system.logo":
            this.appearanceForm.logoUrl = config.configValue;
            break;
          case "system.login.logo":
            this.appearanceForm.loginLogoUrl = config.configValue;
            break;
          case "system.favicon":
            this.appearanceForm.faviconUrl = config.configValue;
            break;
          case "system.login.background":
            this.appearanceForm.loginBackgroundUrl = config.configValue;
            break;
          case "system.theme.color":
            this.appearanceForm.themeColor = config.configValue || "#409EFF";
            break;
          case "system.side.theme":
            this.appearanceForm.sideTheme = config.configValue || "theme-dark";
            break;
          case "system.tagsView":
            this.appearanceForm.tagsView = config.configValue === "true";
            break;
          case "system.fixedHeader":
            this.appearanceForm.fixedHeader = config.configValue === "true";
            break;

          // 功能设置
          case "system.enableRegister":
            this.featureForm.enableRegister = config.configValue === "true";
            break;
          case "system.enableRememberMe":
            this.featureForm.enableRememberMe = config.configValue === "true";
            break;
          case "system.password.expireDays":
            this.featureForm.passwordExpireDays = parseInt(config.configValue) || 90;
            break;
          case "system.password.minLength":
            this.featureForm.passwordMinLength = parseInt(config.configValue) || 8;
            break;
          case "system.password.complexity":
            this.featureForm.passwordComplexity = config.configValue || "medium";
            break;
          case "system.login.failLockCount":
            this.featureForm.loginFailLockCount = parseInt(config.configValue) || 5;
            break;
          case "system.enableWatermark":
            this.featureForm.enableWatermark = config.configValue === "true";
            break;
          case "system.watermark.content":
            this.featureForm.watermarkContent = config.configValue || "{用户名} {部门} {时间}";
            break;
        }
      });
    },

    /** 转换表单数据为配置数组 */
    convertFormToConfigs(formType) {
      const configs = [];

      if (formType === 'basic') {
        // 基本设置表单转换
        configs.push(
          { configKey: "system.title", configValue: this.basicForm.systemTitle, configGroup: "basic" },
          { configKey: "system.short.title", configValue: this.basicForm.systemShortTitle, configGroup: "basic" },
          { configKey: "system.department.id", configValue: this.basicForm.departmentId.toString(), configGroup: "basic" },
          { configKey: "system.support.phone", configValue: this.basicForm.supportPhone, configGroup: "basic" },
          { configKey: "system.description", configValue: this.basicForm.systemDescription, configGroup: "basic" },
          { configKey: "system.copyright", configValue: this.basicForm.copyrightInfo, configGroup: "basic" },
          { configKey: "system.icp", configValue: this.basicForm.icp, configGroup: "basic" }
        );
      } else if (formType === 'appearance') {
        // 外观设置表单转换
        configs.push(
          { configKey: "system.logo", configValue: this.appearanceForm.logoUrl, configGroup: "appearance", configType: "image" },
          { configKey: "system.login.logo", configValue: this.appearanceForm.loginLogoUrl, configGroup: "appearance", configType: "image" },
          { configKey: "system.favicon", configValue: this.appearanceForm.faviconUrl, configGroup: "appearance", configType: "image" },
          { configKey: "system.login.background", configValue: this.appearanceForm.loginBackgroundUrl, configGroup: "appearance", configType: "image" },
          { configKey: "system.theme.color", configValue: this.appearanceForm.themeColor, configGroup: "appearance", configType: "color" },
          { configKey: "system.side.theme", configValue: this.appearanceForm.sideTheme, configGroup: "appearance" },
          { configKey: "system.tagsView", configValue: this.appearanceForm.tagsView.toString(), configGroup: "appearance", configType: "switch" },
          { configKey: "system.fixedHeader", configValue: this.appearanceForm.fixedHeader.toString(), configGroup: "appearance", configType: "switch" }
        );
      } else if (formType === 'feature') {
        // 功能设置表单转换
        configs.push(
          { configKey: "system.enableRegister", configValue: this.featureForm.enableRegister.toString(), configGroup: "feature", configType: "switch" },
          { configKey: "system.enableRememberMe", configValue: this.featureForm.enableRememberMe.toString(), configGroup: "feature", configType: "switch" },
          { configKey: "system.password.expireDays", configValue: this.featureForm.passwordExpireDays.toString(), configGroup: "feature" },
          { configKey: "system.password.minLength", configValue: this.featureForm.passwordMinLength.toString(), configGroup: "feature" },
          { configKey: "system.password.complexity", configValue: this.featureForm.passwordComplexity, configGroup: "feature" },
          { configKey: "system.login.failLockCount", configValue: this.featureForm.loginFailLockCount.toString(), configGroup: "feature" },
          { configKey: "system.enableWatermark", configValue: this.featureForm.enableWatermark.toString(), configGroup: "feature", configType: "switch" },
          { configKey: "system.watermark.content", configValue: this.featureForm.watermarkContent, configGroup: "feature" }
        );
      }

      return configs;
    },

    /** 提交基本设置表单 */
    submitBasicForm() {
      this.$refs.basicForm.validate(valid => {
        if (valid) {
          const configs = this.convertFormToConfigs('basic');
          this.submitConfigs(configs, '基本设置');
        }
      });
    },

    /** 提交外观设置表单 */
    submitAppearanceForm() {
      this.$refs.appearanceForm.validate(valid => {
        if (valid) {
          const configs = this.convertFormToConfigs('appearance');
          this.submitConfigs(configs, '外观设置');
        }
      });
    },

    /** 提交功能设置表单 */
    submitFeatureForm() {
      this.$refs.featureForm.validate(valid => {
        if (valid) {
          const configs = this.convertFormToConfigs('feature');
          this.submitConfigs(configs, '功能设置');
        }
      });
    },

    /** 提交配置数据 */
    submitConfigs(configs, settingType) {
      this.loading = true;
      batchSaveConfig(configs).then(() => {
        this.$modal.msgSuccess(settingType + "保存成功");
        // 更新Store中的设置
        this.updateStoreSettings();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 更新Store中的设置 */
    updateStoreSettings() {
      // 更新主题设置
      if (this.activeTab === 'appearance') {
        this.$store.dispatch('settings/changeSetting', {
          key: 'theme',
          value: this.appearanceForm.themeColor
        });
        this.$store.dispatch('settings/changeSetting', {
          key: 'sideTheme',
          value: this.appearanceForm.sideTheme
        });
        this.$store.dispatch('settings/changeSetting', {
          key: 'tagsView',
          value: this.appearanceForm.tagsView
        });
        this.$store.dispatch('settings/changeSetting', {
          key: 'fixedHeader',
          value: this.appearanceForm.fixedHeader
        });
      }
    },

    /** 重置表单 */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 重新加载配置
      this.getConfigData();
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;

    .header-title {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .el-upload-tip {
    line-height: 1.2;
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
  }

  .color-value {
    margin-left: 10px;
    color: #606266;
  }

  .form-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
  }
}
</style>
